package com.ls.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.config.redis.RedisClient;
import com.ls.config.satoken.SaTokenUtilPy;
import com.ls.controller.ai.model.CreateAIModel;
import com.ls.entity.Company;
import com.ls.entity.Customer;
import com.ls.entity.Holiday;
import com.ls.entity.SmsTemplate;
import com.ls.enums.CallTypeEnum;
import com.ls.enums.RoleEnum;
import com.ls.service.AIService;
import com.ls.service.ICompanyService;
import com.ls.service.ICustomerService;
import com.ls.service.IHolidayService;
import com.ls.utils.ResultData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static com.ls.constant.SystemConstants.APP;
import static com.ls.constant.SystemConstants.NUMBER_0;


@Slf4j
@Service
public class AIServiceImpl implements AIService {
    private final IHolidayService holidayService;
    private final ICompanyService companyService;
    private final RedisClient redisClient;
    @Lazy
    private final ICustomerService customerService;
    @Autowired
    public AIServiceImpl(
            IHolidayService holidayService,
            ICompanyService companyService,
            RedisClient redisClient,
            @Lazy ICustomerService customerService
    ) {
        this.holidayService = holidayService;
        this.companyService = companyService;
        this.redisClient = redisClient;
        this.customerService = customerService;
    }

    @Value("${siliconflow.api-key}")
    private String apiKey;
    @Value("${siliconflow.model-id}")
    private String model;

    public ResultData generateWithQwen(CreateAIModel aimodel) {
        Customer customer1 = SaTokenUtilPy.getCustomer();
        Long customerId = customer1.getCustomerId();
        Customer customer=customerService.getById(customerId);
        if (customer.getAiSmsCount()==NUMBER_0){
            return ResultData.failure("当前用户AI短信数量不足");
        }
        log.info("开始生成AI短信:{}",aimodel);
        try {
            if (StringUtils.isBlank(apiKey) || apiKey.length() < 30) {
                log.error("无效的API密钥配置");
                return ResultData.failure("内部服务器异常");
            }
            String content = "你现在是";
            if (aimodel.getTemplateCategory() == 0) {
                content += "挂机短信";
            } else {
                content += "关怀短信";
            }
            content += "的智能短信生成助手，面向商家服务，根据以下条件以客服的身份回复三条以下短信内容，当对应条件参数为空时忽略：\n";
            if (aimodel.getTemplateCategory() == 0&&aimodel.getCallType() != null) {
                CallTypeEnum callTypeEnum = CallTypeEnum.getRoleEnum(aimodel.getCallType());
                if (CallTypeEnum.OUT_UN_CALL.equals(callTypeEnum)){
                    content+="通话类型：商家拨打用户电话\n";
                }else {
                    content+="通话类型：用户拨打商家电话\n";
                }
                if (CallTypeEnum.IN_REJECTED.equals(callTypeEnum)) {
                    content += "接通状态：拒接" + "\n";
                } else if (CallTypeEnum.IN_UN_CALL.equals(callTypeEnum)) {
                    content += "接通状态：未接通" + "\n";
                } else if (CallTypeEnum.IN_CALL.equals(callTypeEnum)) {
                    content += "接通状态：已接通" + "\n";
                } else if (CallTypeEnum.IN_NOT_DISTURB.equals(callTypeEnum)) {
                    content += "接通状态：勿扰" + "\n";
                } else if (CallTypeEnum.OUT_UN_CALL.equals(callTypeEnum)) {
                    content += "接通状态：呼出" + "\n";
                }
                content+="列如接通状态为呼出，回复类似感谢您的接听之类的内容。\n";
            }
            Company company = companyService.getOne(new LambdaQueryWrapper<Company>()
                    .eq(Company::getCustomerId, customerId));
            if (aimodel.getIsName()!=null&&aimodel.getIsName() == 1) {
                content += "商家名称：" + company.getCompanyName() + "\n";
            }
            if (aimodel.getIsPhone()!=null&&aimodel.getIsPhone() == 1) {
                content += "商家电话：" + company.getPhone() + "\n";
            }
            if (aimodel.getIsAddress()!=null&&aimodel.getIsAddress() == 1) {
                content += "商家地址：" + company.getProvince() + company.getCity() + company.getDistrict() + company.getAddress() + "\n";
            }
            if (StringUtils.isNotEmpty(aimodel.getContent())) {
                content += "同时短信内容中需要融入以下内容，当对应内容参数为空时忽略：" + aimodel.getContent() + "\n";
            }
            if (aimodel.getTemplateCategory() != 0&&aimodel.getHolidayId() != null) {
                Holiday holiday = holidayService.getOne(new LambdaQueryWrapper<Holiday>()
                        .eq(Holiday::getHolidayId, aimodel.getHolidayId()));
                content += "节日类型：" + holiday.getHolidayName() + "\n";
                content+="列如节日类型为春节，回复类似春节快乐之类的内容。\n";
            }
            content += "注意：\n" +
                    "1. 请直接给出短信内容，不用给多余的解释，且短信内容需要直接可用，不需要修改。不需要加“退订回T”类似的内容。\n" +
                    "2. 同时需要特别注意短信内容的合规性，降低终端拦截率。\n" +
                    "3. 短信内容中不要包含短信签名以及【】符号。\n" +
                    "4. 每条短信内容不超过200个字符。\n" +
                    "5. 每次生成三条短信内容。\n"+
                    "6. 每条短信之间没有任何关联，每条短信之间用T分割，只返回短信内容，不返回其他无关内容。\n"+
                    "7. 注意短信内容不要带序号。重点返回内容不能带任何的序号！！！\n"+
                    "8. 注意只返回短信内容，不返回其他无关内容。\n";
            if (aimodel.getTemplateCategory() == 0&&aimodel.getCallType() != null){
                content += "9. 注意基于当前接听状态进行回复。\n";
            }
            if (aimodel.getTemplateCategory() != 0&&aimodel.getHolidayId() != null){
                content += "9. 注意基于当前节日进行回复。\n";
            }
            log.info("生成短信模板内容: {}", content);
            // 构造 JSON 请求体（注意转义引号）
            String jsonBody = String.format(
                    "{\n" +
                            "  \"model\": \"%s\",\n" +
                            "  \"messages\": [\n" +
                            "    {\n" +
                            "      \"role\": \"user\",\n" +
                            "      \"content\": \"%s\"\n" +
                            "    }\n" +
                            "  ]\n" +
                            "}",
                    model, content
            );
            customer.setAiSmsCount(customer.getAiSmsCount()-1);
            customer.updateById();
            log.info("调用customer: {}", customer);
            String cacheKey = APP + "_" + customer.getCustomerId();
            // 使用标准JSON序列化
            redisClient.save(cacheKey, JSON.toJSONString(customer));
            return ResultData.successData(executeAIRequest(jsonBody));
        } catch (Exception e) {
            log.error("调用Qwen API异常: {}", ExceptionUtils.getStackTrace(e));
            return ResultData.failure("内部服务器异常");
        }
    }

    public List<String> getTitle(String url) {
        try {
            // 添加API密钥校验（与generateWithQwen方法保持校验逻辑一致）
            if (StringUtils.isBlank(apiKey) || apiKey.length() < 30) {
                log.error("无效的API密钥配置");
                return null;
            }

            // 优化提示词工程
            String content = String.format("帮我读取文件每个列的列名，直接读取，不需要列名。文件路径：%s。",
                    url);

            // 提取公共请求逻辑到独立方法（与generateWithQwen复用）
            return executeAIRequest(content);
        } catch (Exception e) {
            log.error("文件分析请求异常: {}", ExceptionUtils.getStackTrace(e));
            return null;
        }
    }
    /**获取ai生成次数*/
    @Override
    public ResultData getAICount(){
        Customer customer = SaTokenUtilPy.getCustomer();
        Customer customer1 = customerService.getById(customer.getCustomerId());
        log.info("获取ai短信生成次数：{}", customer);
        return ResultData.successData(customer1.getAiSmsCount());
    }

    // 新增公共请求方法
    private List<String> executeAIRequest(String content) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(1000, TimeUnit.SECONDS)
                .readTimeout(1000, TimeUnit.SECONDS)
                .build();

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", model);
        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", content.replace("\"", "\\\""));
        messages.add(message);
        requestBody.put("messages", messages);

        Request request = new Request.Builder()
                .url("https://api.siliconflow.cn/v1/chat/completions")
                .addHeader("Authorization", "Bearer " + apiKey.trim())
                .post(RequestBody.create(MediaType.parse("application/json"),
                        requestBody.toJSONString()))
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("API请求失败，状态码: {}", response.code());
                return null;
            }

            String responseBody = response.body().string();
            JSONObject result = JSON.parseObject(responseBody);
            log.info("API响应结果: {}", responseBody);
            List<String> msgs = Collections.emptyList();
            if (result.containsKey("choices")) {
                JSONArray choices = result.getJSONArray("choices");
                if (!choices.isEmpty()) {
                    String msg = choices.getJSONObject(0).getJSONObject("message").getString("content");
                    log.info("API响应结果: {}", msg);
                    //将字符串根据T分割
                    msgs = Arrays.asList(msg.split("T"));
                }
            }
            log.info("API响应结果33333333: {}", msgs);
            //将字符串根据T分割
            return msgs;
        }
    }
}